﻿using MimeKit.Text;
using MimeKit;
using PineLake.Drmwe.EMail.MailKitEMail.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PineLake.Drmwe.EMail.MailKitEMail.Services
{
    /// <summary>
    /// MailKit 发送EMail
    /// </summary>
    public class MailServices : IMailServices
    {
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="MailDataModel">发送邮件的实体</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public SendMailMsg SendEMail(MailData MailDataModel)
        {
            var Msg = new SendMailMsg();
            if (string.IsNullOrEmpty(MailDataModel.Account) || string.IsNullOrEmpty(MailDataModel.PassWord))
            {
                Msg.IsSuccess = false;
                Msg.Msg = "发送失败,邮件发送账号,密码不能为空!";
                return Msg;
            }
            if (string.IsNullOrEmpty(MailDataModel.Host))
            {
                Msg.IsSuccess = false;
                Msg.Msg = "发送失败,发送邮件服务器地址不能为空!";
                return Msg;
            }
            if (MailDataModel.Port <= 0 || MailDataModel.Port > 65535)
            {
                Msg.IsSuccess = false;
                Msg.Msg = "发送失败,发送邮件服务器端口不对!";
                return Msg;
            }
            if (string.IsNullOrEmpty(MailDataModel.FromEmail) || !Lib.Regular.Validation.IsEmail(MailDataModel.FromEmail))
            {
                Msg.IsSuccess = false;
                Msg.Msg = "发送失败,邮件发送Email地址不能为空或者格式不对!";
                return Msg;
            }
            if (MailDataModel.ToEMailList.Count == 0)
            {
                Msg.IsSuccess = false;
                Msg.Msg = "发送失败,接收邮件的Email地址不能为空!";
                return Msg;
            }
            if (string.IsNullOrEmpty(MailDataModel.Subject))
            {
                Msg.IsSuccess = false;
                Msg.Msg = "发送失败,发送邮件的标题不能为空!";
                return Msg;
            }
            if (!string.IsNullOrEmpty(MailDataModel.Cc))
            {
                if (!Lib.Regular.Validation.IsEmail(MailDataModel.Cc.Trim()))
                {
                    Msg.IsSuccess = false;
                    Msg.Msg = "发送失败,抄送人邮件的Email地址格式不对!";
                    return Msg;
                }
            }
            //var FileExt = "";
            if (MailDataModel.FileAbsolutePaths != null && MailDataModel.FileAbsolutePaths.Count > 0)
            {
                foreach (var item in MailDataModel.FileAbsolutePaths)
                {
                    var FilePath = item.Trim();
                    if (!File.Exists(FilePath))
                    {
                        Msg.IsSuccess = false;
                        Msg.Msg = $"发送失败,发送的附件 {item} 不存在!";
                        return Msg;
                    }
                }
            }
            var MMessage = new MimeMessage();
            MMessage.From.Add(new MailboxAddress("MailSystem", MailDataModel.FromEmail.Trim())); //发送人

            //接收人
            InternetAddressList ToList = new InternetAddressList();
            foreach (var Toitem in MailDataModel.ToEMailList)
            {
                ToList.Add(new MailboxAddress(Toitem.UserName, Toitem.ToMail));
            }
            MMessage.To.AddRange(ToList); //接收人列表

            MMessage.Subject = MailDataModel.Subject.Trim(); //标题

            //抄送
            if (!string.IsNullOrEmpty(MailDataModel.Cc))
            {
                MMessage.Cc.Add(new MailboxAddress("EMailSystem", MailDataModel.Cc.Trim()));
            }

            var Builder = new BodyBuilder();//Body内容
            //附件列表
            if (MailDataModel.FileAbsolutePaths != null && MailDataModel.FileAbsolutePaths.Count > 0)
            {
                foreach (var item in MailDataModel.FileAbsolutePaths)
                {
                    var FileContent = File.OpenRead(item);
                    var FileName = Path.GetFileName(item);
                    Builder.Attachments.Add(FileName, FileContent);
                }
            }
            //邮件内容
            switch (MailDataModel.BodyContentType)
            {
                case TextFormat.Text:
                    Builder.TextBody = MailDataModel.BodyContent;
                    break;
                case TextFormat.Html:
                    Builder.HtmlBody = MailDataModel.BodyContent;
                    break;
                default:
                    Builder.TextBody = MailDataModel.BodyContent;
                    break;
            }
            MMessage.Body = Builder.ToMessageBody();
            try
            {
                var RetStr = "";
                using (var Smtp = new MailKit.Net.Smtp.SmtpClient())
                {
                    Smtp.Connect(MailDataModel.Host.Trim(), MailDataModel.Port, MailDataModel.IsOpenSSL); //SMTP 服务器建立连接
                    Smtp.Authenticate(MailDataModel.Account.Trim(), MailDataModel.PassWord.Trim());  //用户名 密码(授权码)
                    RetStr = Smtp.Send(MMessage);        //发送
                    Smtp.Disconnect(true);                  //关闭连接
                }
                Msg.Msg = "发送成功!";
            }
            catch (Exception ex)
            {
                Msg.IsSuccess = false;
                Msg.Msg = "邮件发送失败,系统出错!" + "错误信息:" + ex;
            }
            return Msg;
        }
    }
}
